package resources

import (
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

type ArchiveType int

const (
	ArchiveTypeGzip = ArchiveType(iota) + 1
	ArchiveTypeZip
	ArchiveTypeXzip
)

// DataDir 资源根目录，暂时不支持配置
var DataDir = filepath.Join(runtime.Data, "resources")

var once sync.Once
var instance *Resources

func Single() *Resources {
	once.Do(func() {
		if err := os.MkdirAll(DataDir, 0755); nil != err {
			logger.GetLogger().Sugar().Errorf("初始化资源目录失败，失败原因: %s", err)

			os.Exit(1)
		}

		instance = &Resources{path: DataDir, state: map[string]EntryState{}}
	})

	return instance
}

// Resources 简单资源管理器
// 该管理器实现了对文件、文件夹的简单访问和操作
type Resources struct {
	path string

	sm    sync.RWMutex
	state map[string]EntryState
}

// normal 对路径进行标准处理
func (cls *Resources) normal(paths []string) (string, error) {
	var path = strings.Trim(filepath.Clean(filepath.Join(paths...)), "/")

	// 不允许在任何层级存在相对路径
	if strings.Contains(path, "..") {
		return "", errors.New("非法路径")
	}

	return path, nil
}
